#include "cms8s6990.h"
#include "soc_timer.h"

uint16_t m_timerCounts[] = {0, 0, 0, 0};

void SOC_TimerInit(SOC_TimerNo_t no, uint32_t us)
{
	/*
	(1)设置Timer的运行模式
	*/
	TMR_ConfigRunMode(no, TMR_MODE_TIMING,TMR_TIM_16BIT);	
	/*
	(2)设置Timer 运行时钟
	*/
	TMR_ConfigTimerClk(no, TMR_CLK_DIV_12);						/*Fsys = 24Mhz，Ftimer = 2Mhz,Ttmr=0.5us*/
	/*
	(3)设置Timer周期
	*/	
	SOC_TimerSetTimeOut(no, us); 				// 200*0.5us = 100us,递增计数
		
	/*
	(4)开启中断
	*/
	TMR_EnableOverflowInt(no);

	/*
	(5)设置Timer中断优先级
	*/	
	// IRQ_SET_PRIORITY(no, IRQ_PRIORITY_LOW);
}

void SOC_TimerSetTimeOut(SOC_TimerNo_t no, uint32_t us)
{
	uint16_t count = (uint16_t)(us / (12000000.0 / SOC_GetCpuFrequency()) + 0.5);

	m_timerCounts[no] = count;
	TMR_ConfigTimerPeriod(no, (65536-count)>>8, 65536-count); 
}

void SOC_TimerReload(SOC_TimerNo_t no) 
{
	uint16_t count = m_timerCounts[no];

	TMR_ConfigTimerPeriod(no, (65536-count)>>8, 65536-count); 
}

void SOC_TimerStart(SOC_TimerNo_t no)
{
	TMR_Start(no);
}

void SOC_TimerStop(SOC_TimerNo_t no)
{
	TMR_Stop(no);
}
